﻿using CommonBase.ResponseBase;
using CustomControls.PoptipCtr.Base;
using LogProjectManager;
using ManagementToolClient.BaseViewModels;
using ManagementToolClient.Models;
using Newtonsoft.Json;
using Prism.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using System.IO;
using CustomControls.PoptipCtr;

namespace ManagementToolClient.ViewModels
{
    internal class AddUpdateFileViewModel : MiddleDalogViemModelBase, ILayDialogWindowAware
    {
        public new event Action<ILayDialogResult> RequestClose;

        private string ModuleID { set; get; }

        private string DeviceID { set; get; }

        private string _SelectFilePath = "";
        public string SelectFilePath 
        {
            get { return _SelectFilePath; }
            set
            {
                SetProperty(ref _SelectFilePath, value);

            }
        }


        private DeviceModeuleManagerModel _ModuleManagerItem;

        public DeviceModeuleManagerModel ModuleManagerItem
        {
            get { return _ModuleManagerItem; }
            set
            {
                SetProperty(ref _ModuleManagerItem, value);

            }
        }

        #region cmd
        private DelegateCommand _CloseCommand;
        public DelegateCommand CloseCommand =>
            _CloseCommand ?? (_CloseCommand = new DelegateCommand(ExcuteCloseCommand));



        private DelegateCommand _OKxCommand;
        public DelegateCommand OKxCommand =>
            _OKxCommand ?? (_OKxCommand = new DelegateCommand(ExcuteOKxCommand));


        private DelegateCommand _SelectFileCommand;
        public DelegateCommand SelectFileCommand =>
            _SelectFileCommand ?? (_SelectFileCommand = new DelegateCommand(ExcuteSelectFileCommand));

       

        #endregion


        public new bool CanCloseDialog()
        {
            return true;
        }

        public new void OnDialogClosed()
        {

        }



        public void OnDialogOpened(ILayDialogParameter parameters)
        {
            ModuleID = parameters.GetValue<string>("ModuleID");
            DeviceID = parameters.GetValue<string>("DeviceID");
            ModuleManagerItem = new DeviceModeuleManagerModel();
        }

        private void ExcuteCloseCommand()
        {
            BackPageCommandMethod(ButtonResult.No);
        }

        private void ExcuteSelectFileCommand()
        {
            System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
            openFileDialog.Multiselect = false;

            openFileDialog.Filter = "压缩文件|*.zip;*.rar;*.7z;";
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
            {
                SelectFilePath = openFileDialog.FileName;
            }
        }

        private void ExcuteOKxCommand()
        {
            Task.Run(async () => {
                try
                {
                    var url = "http://127.0.0.1:8081" + "/api/ToUploadFile/ToUploadFileAsync?" + $"_moduleid={ModuleID}" + "&" + $"_deviceid={DeviceID}" + "&" + $"_version={ModuleManagerItem.version}";

                    try
                    {
                        var httpClient = new HttpClient();

               
                        var formContent = new MultipartFormDataContent();


                        var fileName = System.IO.Path.GetFileName(SelectFilePath);
                        var fileContent = System.IO.File.ReadAllBytes(SelectFilePath);
                        formContent.Add(new ByteArrayContent(fileContent), "files", fileName);
                        // 发送 HTTP POST 请求，并将 multipart 表单数据作为请求体传输
                        var response = httpClient.PostAsync(url, formContent).Result;
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            string responseBody = await response.Content.ReadAsStringAsync();
                            ResponseBody resulRespons = JsonConvert.DeserializeObject<ResponseBody>(responseBody);
                            if (resulRespons.Code == ErrorCode.OK)
                            {
                              
                                LogManager.WriteLog(LogTypeEnum.Normal, "UplodLogFile", $"后台上传：{SelectFilePath}成功!");
                                BackPageCommandMethod(ButtonResult.Yes);
                            }
                            else
                            {
                                MessageControl.Warning(resulRespons.description, "RootMessageTooken");
                                LogManager.WriteLog(LogTypeEnum.Exception, "UplodLogFile", $"后台上传：{SelectFilePath}失败,错误码:{resulRespons.description}!");
                            }

                        }
                        else
                        {                       
                            LogManager.WriteLog(LogTypeEnum.Exception, "UplodLogFile", $"后台上传：{SelectFilePath}失败,错误码:{response.StatusCode}!");
                        }

                    }
                    catch (Exception ex)
                    {
                    
                        LogManager.WriteLog(LogTypeEnum.Exception, "UplodLogFile", ex.ToString());
                    }

                }
                catch (Exception ex)
                {
                    LogManager.WriteLog(LogTypeEnum.Exception, "GetDate", ex.Message);
                }
            });
        }


        private void BackPageCommandMethod(ButtonResult itemResult)
        {
            LayDialogResult dialogResult = new LayDialogResult();
            dialogResult.Result = itemResult;
            RequestClose?.Invoke(dialogResult);
        }
    }
}
